//
//  mm_otherChargeViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-20.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_otherChargeViewController.h"

@interface mm_otherChargeViewController ()<ContentViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *projectNameBtn;

@property (strong, nonatomic) IBOutlet UITextField *projectAmountTxt;
@property (weak, nonatomic) IBOutlet UIButton *chargeDiffBtn;

/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;
@property(nonatomic,strong)NSMutableDictionary *chargeDiffValKey;

/** 附加项目名称列表 */
@property(nonatomic,strong)NSMutableArray *projectNameKeys;
@property(nonatomic,strong)NSMutableArray *projectPriceKeys;
@property(nonatomic,strong)NSMutableDictionary *projectNameDic;
@property(nonatomic,strong)NSMutableDictionary *projectCodeDic;

/** 维修分类 */
@property(nonatomic,strong)NSMutableArray *repairTypeNames;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property(nonatomic,strong)NSMutableDictionary *repairTypeCodeDic;
@property (weak, nonatomic) IBOutlet UIButton *repairTypeBtn;
@end

@implementation mm_otherChargeViewController
-(NSMutableArray *)repairTypeNames{
    if (_repairTypeNames == nil) {
        _repairTypeNames= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        _repairTypeCodeDic=[NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeNames addObject:name];
            [_repairTypeDic setObject:val forKey:name];
            [_repairTypeCodeDic setObject:name forKey:val];
        }
    }
    return _repairTypeNames;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.frame = CGRectMake(0, 0, 500, 600);
    if (!self.newOperation) {
        //初始化数据
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        NSDictionary *dicTmp = modelIns.attachProjects[modelIns.nRowForOtherChargeList];
        if (dicTmp) {
            [self chargeDiffKeys];
            [self projectNameKeys];
            [self repairTypeNames];
            [self.chargeDiffBtn setTitle:self.chargeDiffValKey[dicTmp[@"CHARGE_PARTITION_CODE"]] forState:UIControlStateNormal];
            [self.projectNameBtn setTitle:self.projectCodeDic[dicTmp[@"ADD_ITEM_CODE"]] forState:UIControlStateNormal];
            NSString*addAmount=[NSString stringWithFormat:@"%.2f",[dicTmp[@"ADD_ITEM_AMOUNT"] doubleValue]];
            self.projectAmountTxt.text = addAmount;
            
            [self.repairTypeBtn setTitle:self.repairTypeCodeDic[dicTmp[@"REPAIR_TYPE_CODE"]] forState:UIControlStateNormal];
        }
    }
    
    [self registerNotificationForKeyBoard];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 保存数据的方法

-(BOOL)saveData
{
    if (self.projectNameBtn.titleLabel.text.length<=0){
        return true;//如果每天写任何东西就直接dissmiss 窗口
    }
    
    NSString *msg = [self getErrorMsg];
    if (msg) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return false;
    }
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *chargeDiffVal = self.chargeDiff[self.chargeDiffBtn.titleLabel.text];
    if (!chargeDiffVal) {
        chargeDiffVal = @"";
    }
    NSString *projectName = self.projectNameBtn.titleLabel.text;//附加项目名称
    NSString *projectCode = self.projectNameDic[projectName];
    NSString*repairType=self.repairTypeDic[self.repairTypeBtn.currentTitle];
    NSMutableDictionary *data = nil;
    NSString *status = @"";
    if (self.newOperation) {//新增操作
        data = [NSMutableDictionary dictionary];
        [data setObject:@"" forKey:@"ITEM_ID"];
        status = @"A";
    }else{
        data = modelIns.attachProjects[modelIns.nRowForOtherChargeList];
        NSString*itemID=[NSString stringWithFormat:@"%zd",[data[@"ITEM_ID"] integerValue]];
        if (![itemID isEqualToString:@"0"]) {
           status = @"U";
        }else{
           status = @"A";
        }
        
    }
    [data setObject:status forKey:@"STATUS"];
    [data setObject:@(self.discount) forKey:@"DISCOUNT"];
    [data setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    [data setObject:projectName forKey:@"ADD_ITEM_NAME"];//附加项目名称
    [data setObject:projectCode forKey:@"ADD_ITEM_CODE"];//附加项目代码
    [data setObject:repairType forKey:@"REPAIR_TYPE_CODE"];//维修分类
    [data setObject:self.projectAmountTxt.text forKey:@"ADD_ITEM_AMOUNT"];//金额
    if (self.newOperation) {
        [modelIns.attachProjects addObject:data];
    }
    return true;
}

-(NSString *)getErrorMsg{
    NSString *msg = nil;
    if (self.projectAmountTxt.text.length<=0){
        msg = @"请输入附加项目费！";
    }else if (self.chargeDiffBtn.titleLabel.text.length<=0){
        msg = @"请选择收费区分";
    }else if (!self.repairTypeBtn.currentTitle.length){
         msg = @"请选择维修分类";
    }
    return msg;
}

#pragma mark - 键盘托起屏幕的代理方法

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    int offset = 150;//键盘高度350
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.superview.frame.size.width;
    float height = self.view.superview.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.superview.frame = rect;
    }
    [UIView commitAnimations];
}

//注册键盘消息
-(void)registerNotificationForKeyBoard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setViewNormal) name:UIKeyboardWillHideNotification object:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

//视图回归正常状态
-(void)setViewNormal
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
}

- (IBAction)projectNameBtnClicked:(UIButton *)sender {
    //创建下拉菜单
    [self createThePopViewControl:sender];
    //刷新下拉菜单数据
    contentCon.list = self.projectNameKeys;
    [contentCon.myTableView reloadData];
}
- (IBAction)clickSelectRepairType:(id)sender {
    //创建下拉菜单
    [self createThePopViewControl:sender];
    NSArray *source = nil;
    source = self.repairTypeNames;
    contentCon.list = source;
    [contentCon.myTableView reloadData];
}

- (IBAction)chargeDiffBtnClicked:(UIButton *)sender {
    //创建下拉菜单
    [self createThePopViewControl:sender];
    //刷新下拉菜单数据
    contentCon.list = self.chargeDiffKeys;
    [contentCon.myTableView reloadData];
}

#pragma mark -懒加载
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        _chargeDiffValKey = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if ([name isEqualToString:@"自费"]||[name isEqualToString:@"免费"]||[name isEqualToString:@"保险"]||[name isEqualToString:@"店端活动"]||[name isEqualToString:@"客户活动"]) {
                [_chargeDiffKeys addObject:name];
                [_chargeDiff setObject:val forKey:name];
                [_chargeDiffValKey setObject:name forKey:val];
            }
           
        }
    }
    return _chargeDiffKeys;
}

-(NSMutableArray *)projectNameKeys{
    if (_projectNameKeys == nil) {
        NSMutableArray *arr = [self readershuDICimform][@"TM_BALANCE_MODE_ADD_ITEM"];
        _projectNameKeys = [NSMutableArray array];
        _projectPriceKeys = [NSMutableArray array];
        _projectNameDic = [NSMutableDictionary dictionary];
        _projectCodeDic = [NSMutableDictionary dictionary];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"ADD_ITEM_NAME"];
            NSString *val = dic[@"ADD_ITEM_CODE"];
            [_projectNameKeys addObject:name];
            [_projectPriceKeys addObject:dic[@"ADD_ITEM_PRICE"]];
            [_projectNameDic setObject:val forKey:name];
            [_projectCodeDic setObject:name forKey:val];
        }
    }
    return _projectNameKeys;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

#pragma mark - 创建下拉菜单方法
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!contentCon)
    {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    contentCon.delegate = self;
    contentCon.btnSender=sender;
    
    popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *text = nil;
    if (btn == self.chargeDiffBtn) {
        text = self.chargeDiffKeys[row];
    }else if (btn == self.projectNameBtn){
        text = self.projectNameKeys[row];
        self.projectAmountTxt.text = [self.projectPriceKeys[row]stringValue];
    }else if (btn==self.repairTypeBtn){
        text=self.repairTypeNames[row];
    }
    [btn setTitle:text forState:UIControlStateNormal];
    
    //清空数据，退出控件
    [popCon dismissPopoverAnimated:YES];
    popCon = nil;
}

@end
